package com.xuliucar.car.ui.fragment

import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.content.*
import android.graphics.*
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import android.os.IBinder
import android.os.SystemClock
import android.text.TextUtils
import android.util.DisplayMetrics
import android.util.Log
import android.view.Gravity
import android.view.ViewGroup
import android.view.Window
import android.widget.ImageView
import android.widget.SeekBar
import com.cangmaomao.lib.base.BaseFragment
import com.cangmaomao.lib.config.TAG
import com.cangmaomao.lib.utils.*
import com.cangmaomao.lib.utils.FileUtils.saveDraw
import com.cangmaomao.lib.utils.SPUtil.create
import com.google.common.collect.ArrayListMultimap
import com.tqltech.tqlpencomm.Dot
import com.tqltech.tqlpencomm.PenCommAgent
import com.xuliucar.car.R
import com.xuliucar.car.contract.EditHandwritingContract
import com.xuliucar.car.event.ColorEvent
import com.xuliucar.car.service.BluetoothLEService
import com.xuliucar.car.service.ScreenRecorder
import com.xuliucar.car.view.dialog.ColorPop
import com.xuliucar.car.view.dialog.DrawView
import kotlinx.android.synthetic.main.f_edit_handwriting.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.io.ObjectOutputStream
import java.text.SimpleDateFormat
import java.util.*

/**
 * 编辑笔迹
 */
class EditHandwriting : BaseFragment<EditHandwritingContract.Presenter>(), EditHandwritingContract.View {

    var color: Int = 0
    private var colorPop: ColorPop? = null
    lateinit var sp: SPUtil
    lateinit var c: Activity
    var mWidth: Float = 0.toFloat()
    var mHeight: Float = 0.toFloat()
    lateinit var param: ViewGroup.LayoutParams
    lateinit var mBluetooth: BluetoothAdapter
    var mac: String? = ""
    var gColor: Int = 0
    private val BG_REAL_WIDTH = 909
    private val BG_REAL_HEIGHT = 1281
    private var ratio: Float = 0F
    private lateinit var filePath: String;
    var pageIdIndex: Int = 0//保存当前页码
    private var status: Int = 0
    private lateinit var mMediaProjectionManager: MediaProjectionManager
    var bitmap: Bitmap? = null
    var bitmpResult: Bitmap? = null


    override val contentViewLayoutID: Int
        get() = R.layout.f_edit_handwriting

    override fun initView(savedInstanceState: Bundle?) {
        initToolBarNav(getFileName(), "保存")
        c = mContext as Activity
        getScreenBaseInfo()
        sp = create("DrawViewColor")
        mac = create("BleConfig").get("mac", "") as String
        e("地址  " + mac)
        gColor = TypeUtils.paseInt("000000")
        mBluetooth = BluetoothAdapter.getDefaultAdapter()
        bleManager = PenCommAgent.GetInstance(c.getApplication())
        mRxPermissions!!.request(Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.ACCESS_FINE_LOCATION).subscribe({
            if (!mBluetooth.isEnabled()) {
                toast("打开蓝牙成功")
                mBluetooth.enable()
            }
            val gattServiceIntent = Intent(c, BluetoothLEService::class.java)
            c.bindService(gattServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE)
        }, {
            pop()
            return@subscribe
        })

        //0 --> 代表录屏
        if (status != 0) {
            mMediaProjectionManager = _mActivity.getSystemService(Context.MEDIA_PROJECTION_SERVICE)
                    as MediaProjectionManager
            val captureIntent = mMediaProjectionManager.createScreenCaptureIntent()
            startActivityForResult(captureIntent, 1001)
        }
        bDrawl[0] = DrawView(mContext)
        gImageView.isDrawingCacheEnabled = true
        bDrawl[0]!!.setVcolor(Color.BLACK)
        val dm = DisplayMetrics()
        c.windowManager.defaultDisplay.getMetrics(dm)
        mWidth = dm.widthPixels.toFloat()
        mHeight = dm.heightPixels.toFloat()
        param = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT)
        param.width = mWidth.toInt()
        param.height = mHeight.toInt()
        mylayout.addView(bDrawl[0], param)
        drawInit()
        getWindowInfo()
        listener()
    }

    fun getWindowInfo() {
        if (mWidth == 1536f && mHeight == 2048f) {
            ratio = mWidth * 63 / 72 / BG_REAL_WIDTH
        } else {
            ratio = mWidth * 70 / 72 / BG_REAL_WIDTH
        }
        BG_WIDTH = (BG_REAL_WIDTH * ratio).toInt()
        BG_HEIGHT = (BG_REAL_HEIGHT * ratio).toInt()
        gcontentLeft = c.window.findViewById<ViewGroup>(Window.ID_ANDROID_CONTENT).getLeft()
        gcontentTop = c.window.findViewById<ViewGroup>(Window.ID_ANDROID_CONTENT).getTop()
        A5_X_OFFSET = (mWidth - gcontentLeft.toFloat() - BG_WIDTH.toFloat()).toInt() / 2
        A5_Y_OFFSET = (mHeight - gcontentTop.toFloat() - BG_HEIGHT.toFloat()).toInt() / 2
    }


    override fun getFileName(): String {
        filePath = arguments!!.getString("filePath")
        status = arguments!!.getInt("status")
        return arguments!!.getString("fileName")
    }

    override fun onRightClick() {
        if (status == 0) {
            bitmap = BitMaps.captureWindowView(_mActivity)
            bitmpResult = BitMaps.createBitmap(bitmap, gImageView.x.toInt(), gImageView.y.toInt()
                    , gImageView.width, gImageView.height)
            saveDraw(filePath, pageIdIndex.toString(), bitmpResult)
        } else {
            mRecorder!!.quit()
            mRecorder = null
        }
        toast("保存成功")
        startWithPopTo(MainFragment(), EditHandwriting::class.java, false)
    }

    fun listener() {
        view6.setOnClickListener {
            opeAdvancenDialog()
        }
        view3.max = 30
        val listener: SeekBar.OnSeekBarChangeListener = object : SeekBar.OnSeekBarChangeListener {
            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
//                mDrawView.setVwidth(progress)
            }
        }
        view3.setOnSeekBarChangeListener(listener)
        view1.setOnClickListener {
            toast(" 暂不支持")
        }
        view2.setOnClickListener {
            toast(" 暂不支持")
        }
    }

    private fun opeAdvancenDialog() {
        if (colorPop == null) {
            colorPop = ColorPop(mContext, create("colorList"))
        }
        val location = IntArray(2)
        view_bottom_2.getLocationOnScreen(location)
        colorPop!!.showAtLocation(view_bottom_2, Gravity.NO_GRAVITY, location[0], location[1] - _mActivity.dp2px<Int>(50f))
        if (!colorPop!!.isShowing) {
            val c = mContext as Activity
            colorPop!!.backgroundAlpha(c, 1f)
        }
        val colorlistener: ColorPop.colorCall = object : ColorPop.colorCall {
            override fun colorData(color: Int) {
                saveDrawViewColor(color)
                e("color = " + color)
                SetPenColor(color)
                colorPop!!.dismiss()
            }
        }
        colorPop!!.setColorData(colorlistener)

    }

    //保存修改的画布颜色
    fun saveDrawViewColor(color: Int) {
        sp.add("ViewColor", color.toString())
    }

    /******画板操作********/
    private var mService: BluetoothLEService? = null
    private val REQUEST_SELECT_DEVICE = 1
    private val REQUEST_ENABLE_BT = 2

    private val A5_WIDTH = 154.4
    private val A5_HEIGHT = 217.4
    private var bofflineNum = 0
    private var bIsFinishDownload = false
    private var gofflineNum = 0
    private var pointX: Float = 0.toFloat()
    private var pointY: Float = 0.toFloat()
    private val pointX123 = FloatArray(3)
    private val pointY123 = FloatArray(3)
    private var pointZ: Int = 0
    private var gpointX: Float = 0.toFloat()
    private var gpointY: Float = 0.toFloat()
    private var tmpx: Long = 0
    private var tmpy: Long = 0
    private val bDrawl = arrayOfNulls<DrawView>(2)  //add 2016-06-15 for draw
    private var mov_x: Float = 0.toFloat()//声明起点坐标
    private var mov_y: Float = 0.toFloat()//声明起点坐标
    private var omov_x: Float = 0.toFloat()
    private var omov_y: Float = 0.toFloat()
    private var gFlyPtCount = 0
    private var pointORGX = 0f
    private var pointORGY = 0f
    private var BG_WIDTH: Int = 0
    private var BG_HEIGHT: Int = 0
    private var BG_WIDTH1: Int = 0
    private var BG_HEIGHT1: Int = 0
    private var A5_X_OFFSET: Int = 0
    private var A5_Y_OFFSET: Int = 0
    private var gcontentLeft: Int = 0
    private var gcontentTop: Int = 0
    /////modified 2016-06-15 start
    private val NUMBER = 10000
    private val STROKENO = 30000
    private val PAGENO = 100
    private val PENLEN_DISTANCE = 4.0641
    private val XDIST_PERUNIT = 1.3547
    private val YDIST_PERUNIT = 1.3758
    private var jason_txt = ""
    private val oos: ObjectOutputStream? = null
    private val bIsA5size = true
    var g_x0: Float = 0.toFloat()
    var g_x1: Float = 0.toFloat()
    var g_x2: Float = 0.toFloat()
    var g_x3: Float = 0.toFloat()
    var g_y0: Float = 0.toFloat()
    var g_y1: Float = 0.toFloat()
    var g_y2: Float = 0.toFloat()
    var g_y3: Float = 0.toFloat()
    var g_p0: Float = 0.toFloat()
    var g_p1: Float = 0.toFloat()
    var g_p2: Float = 0.toFloat()
    var g_p3: Float = 0.toFloat()
    var g_vx01: Float = 0.toFloat()
    var g_vy01: Float = 0.toFloat()
    var g_n_x0: Float = 0.toFloat()
    var g_n_y0: Float = 0.toFloat()
    var g_vx21: Float = 0.toFloat()
    var g_vy21: Float = 0.toFloat()
    var g_norm: Float = 0.toFloat()
    var g_n_x2: Float = 0.toFloat()
    var g_n_y2: Float = 0.toFloat()
    var gbEverZoom = false
    private var gbSetNormal = false
    private var gbReplay = false
    private var gbStopReplay = false
    private var gbCover = false
    private var gPIndex = -1

    //    var gCurPageID = -1
    companion object {
        var gCurPageID = -1
    }

    private var bIsOfficeLine = false
    private var firstXy = false
    private var index = 0
    var mN: Int = 0
    var gScale = 1f
    var gOffsetX = 0f
    var gOffsetY = 0f

    private var gWidth = 3
    private var width1: Int = 0
    private var gSpeed = 30
    private var stroke_c: IntArray? = IntArray(PAGENO)
    private val point_c = IntArray(PAGENO)
    internal var dot_number: ArrayListMultimap<Int, Dots>? = ArrayListMultimap.create()
    private var count = 0
    internal lateinit var bleManager: PenCommAgent
    protected var mDrawPath = Path()

    private val mServiceConnection = object : ServiceConnection {

        override fun onServiceConnected(className: ComponentName, rawBinder: IBinder) {
            mService = (rawBinder as BluetoothLEService.LocalBinder).service
            Log.e(TAG, "onServiceConnected mService= " + mService!!.initialize())
            if (!mService!!.initialize()) {
                toast("蓝牙未连接成功")
                Log.e(TAG, "Unable to initialize Bluetooth")
                pop()
            }
            if (!TextUtils.isEmpty(mac)) {
                mService!!.connect(mac)
            }
            mService!!.setOnDataReceiveListener(object : BluetoothLEService.OnDataReceiveListener {
                override fun onDataReceive(dot: Dot) {

                    c.runOnUiThread(Runnable {
                        try {
                            ProcessDots(dot)
                        } catch (e: Exception) {
                            Log.e(TAG, e.toString())
                        }
                    })
                }

                override fun onOfflineDataReceive(dot: Dot) {
                    c.runOnUiThread(Runnable {
                        try {
                            bofflineNum++
                            ProcessDots(dot)
                        } catch (e: Exception) {
                            Log.e(TAG, e.toString())
                        }
                    })
                }

                override fun onFinishedOfflineDown(success: Boolean) {
                    bIsFinishDownload = success

                    // 离线数据获取完成后，清除
//                    if (success == true) {
//                        bleManager.RemoveOfflineData(0, 0)
//                    }
                }

                override fun onOfflineDataNum(num: Int) {
                    gofflineNum = num
                    handler.obtainMessage(0x123, gofflineNum).sendToTarget()
                }
            })
        }

        override fun onServiceDisconnected(classname: ComponentName) {
            mService = null
        }
    }

    private var mRecorder: ScreenRecorder? = null

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val mediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data)
        recordVideo(mediaProjection!!)
    }

    private fun recordVideo(mediaProjection: MediaProjection) {
        val file = File(filePath, getFileName() + ".mp4")
        val bitrate = 6000000
        mRecorder = ScreenRecorder(1280, 720, bitrate,
                1, mediaProjection, file.absolutePath)
        if (mRecorder != null) {
            mRecorder!!.start()
            toast("开始录制")
        }

    }


    var mScreenWidth: Int = 0
    var mScreenHeight: Int = 0
    var mScreenDensity: Int = 0
    private fun getScreenBaseInfo() {
        val metrics = DisplayMetrics()
        c.getWindowManager().getDefaultDisplay().getMetrics(metrics)
        mScreenWidth = metrics.widthPixels
        mScreenHeight = metrics.heightPixels
        mScreenDensity = metrics.densityDpi
    }

    private var bIsReply = false

    private fun ProcessDots(dot: Dot) {
        Log.e("TAG1", dot.toString())
        // 回放模式，不接受点
        if (bIsReply == true) {
            return
        }
        ProcessEachDot(dot)
    }

    private fun ProcessEachDot(dot: Dot) {
        val counter = 0
        val time: Long
        pointZ = dot.force

        if (pointZ < 0 && pointZ != 0) {
            Log.e(TAG, "Counter=$counter, Pressure=$pointZ  Cut!!!!!")
            return
        }

        val format1 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        //String str = format1.format(new java.util.Date());
        try {
            Log.e(TAG, "sad222222")
            //String str = "2010-01-02 00:00:00";
            val str1 = "2010-01-01 00:00:00"
            //Date d1 = format1.parse(str);
            val d2 = format1.parse(str1)

            val timeOrig = d2.time
            val timeCurr = (timeOrig + dot.timelong) / 1000

            var time1 = ""
            time1 = timedate(timeCurr)
            Log.e(TAG, "========currentTime=======" + d2.time + ", " + timeCurr + ", " + time1)
        } catch (e: Exception) {
        }

        tmpx = dot.x.toLong()

        pointX = dot.fx.toFloat()
        //pointX /= 128.0;
        pointX /= 100.0f
        pointX += tmpx.toFloat()

        tmpy = dot.y.toLong()

        pointY = dot.fy.toFloat()
        //pointY /= 128.0;
        pointY /= 100.0f
        pointY += tmpy.toFloat()

        if (pointY > 1540 || pointX > 1100) {
            return
        }

        time = dot.timelong
        if (pointZ > 0) {
            omov_x = pointX
            omov_y = pointY
            gFlyPtCount = 0
        }
        //Log.e(TAG,"X:"+pointX+", Y:"+pointY);
        pointORGX = pointX
        pointORGY = pointY
        gpointX = pointX
        gpointY = pointY
        pointX *= BG_WIDTH.toFloat()
        val ax = (A5_WIDTH / XDIST_PERUNIT).toFloat()
        pointX /= ax

        pointY *= BG_HEIGHT.toFloat()
        val ay = (A5_HEIGHT / YDIST_PERUNIT).toFloat()
        pointY /= ay

        ////////////////////////////2016-06-28 for draw end
        pointX += A5_X_OFFSET.toFloat()
        pointY += A5_Y_OFFSET.toFloat()
        Log.e(TAG, ":::::::::::::$pointX--$pointY")
        val text: String
        //messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
        val path = "/sdcard/Test/"
        var txt = ""
        Log.e(TAG, "=========" + pointZ)
        // String jason_txt = "";
        if (pointZ > 0) {
            if (dot.type == Dot.DotType.PEN_DOWN) { //Pen Down
                txt = "===============PEN_DOWN====================="
                Log.e(TAG, "=====PEN_DOWN1====")

                // 2017.11.27 jason
                jason_txt = "{\n" +
                        "\"data\":\n" +
                        "{\n" +
                        "\"pageID\":1,\n" +
                        "\"line_width\":2,\n" +
                        "\"color\":422232,\n" +
                        "\"points\":\n" +
                        "[" + java.lang.Float.toString(gpointX) + "," + java.lang.Float.toString(gpointY) + ","

                //writeTxtToFile(txt, path, gFileName);
                gPIndex = 0
                val PageID: Int
                if (gbReplay == true) {
                    gbStopReplay = true
                    SystemClock.sleep(50)
                    drawInit()
                    Log.e(TAG, "First DrawExistingStroke======" + gCurPageID)
                    DrawExistingStroke(gCurPageID)
                }
                //PageID = CheckXYLocation(gpointX, gpointY);
                PageID = dot.PageID
                Log.e(TAG, "=====PEN_DOWN2====" + PageID)
                if (PageID != gCurPageID || gbEverZoom == true) {
                    Log.e(TAG, "=====PEN_DOWN3====" + gCurPageID)
                    SetBackgroundImage(PageID)
                    Log.e(TAG, "=====PEN_DOWN4====")
                    bIsOfficeLine = true
                    gCurPageID = PageID
                    drawInit()
                    Log.e(TAG, "Second DrawExistingStroke======" + gCurPageID)
                    DrawExistingStroke(gCurPageID)
                    gbEverZoom = false
                }
                SetPenColor(gColor)
                drawSubFountainPen(bDrawl[0]!!, gScale, gOffsetX, gOffsetY, gWidth, pointX, pointY, pointZ) //gPindex=0
                firstXy = true
                Log.e(TAG, "Dot.DotType.PEN_DOWN======")
                // 保存屏幕坐标，原始坐标会使比例缩小
                saveData(gCurPageID, pointX, pointY, pointZ, 0, width1, gColor, dot.Counter, dot.angle)
                point_c[gCurPageID]++
                mov_x = pointX
                mov_y = pointY
                return
            }
            if (dot.type == Dot.DotType.PEN_MOVE) { // Pen Move
                gPIndex += 1
                mN += 1
                Log.e(TAG, "----------move---------")
                jason_txt += java.lang.Float.toString(gpointX) + "," + java.lang.Float.toString(gpointY) + ","
                SetPenColor(gColor)
                drawSubFountainPen(bDrawl[0]!!, gScale, gOffsetX, gOffsetY, gWidth, pointX, pointY, pointZ)
                bDrawl[0]!!.invalidate(Math.min(mov_x, pointX).toInt() - 30, Math.min(mov_y, pointY).toInt() - 30, Math.max(mov_x, pointX).toInt() + 30, Math.max(mov_y, pointY).toInt() + 30)
                mov_x = pointX
                mov_y = pointY

                // 保存屏幕坐标，原始坐标会使比例缩小
                saveData(gCurPageID, pointX, pointY, pointZ, 1, width1, gColor, dot.Counter, dot.angle)
                point_c[gCurPageID]++
            }
        } else if (dot.type == Dot.DotType.PEN_UP) { // Pen Up

            txt = "===============PEN_UP====================="
            //writeTxtToFile(txt, path, gFileName);
            //Log.e(TAG, "3 PID = "+CurPenID);
            stroke_c!![gCurPageID]++
            jason_txt += java.lang.Float.toString(gpointX) + "," + java.lang.Float.toString(gpointY) + "]\n" +
                    "}\n" +
                    "}\n"

            if (dot.x == 0 || dot.y == 0) {
                pointX = mov_x
                pointY = mov_y
            }

            index += 1
            drawSubFountainPen(bDrawl[0]!!, gScale, gOffsetX, gOffsetY, gWidth, pointX, pointY, pointZ)

            // 保存屏幕坐标，原始坐标会使比例缩小
            saveData(gCurPageID, pointX, pointY, pointZ, 2, width1, gColor, dot.Counter, dot.angle)
            bDrawl[0]!!.invalidate()
            pointX = 0f
            pointY = 0f
            firstXy = false
            mN = 0
            gPIndex = -1

        }
    }

    private fun saveData(pageID: Int?, pointX: Float, pointY: Float, force: Int,
                         ntype: Int, penWidth: Int, color: Int, counter: Int, angle: Int) {
        val dot = Dots(pointX, pointY, force, ntype, penWidth, color, counter, angle)
        dot_number!!.put(pageID, dot)
    }

    fun timedate(time: Long?): String {
        val sdr = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val i = Integer.parseInt(time.toString())//long lcc = Long.valueOf(time);
        return sdr.format(Date(i * 1000L))
    }


    private fun drawSubFountainPen(DV: DrawView, scale: Float, offsetX: Float,
                                   offsetY: Float, penWidth: Int, x: Float, y: Float, force: Int) {
//        val scaled_pen_thickness = getScaledPenThickness(mPenThickness.toFloat(), scale)
        if (gPIndex == 0) {
            g_x0 = x * scale + offsetX + 0.1f
            g_y0 = y * scale + offsetY
            g_p0 = Math.max(1f, penWidth.toFloat() * scale * force.toFloat() / 1023)
            //g_p0 = 5;
            width1 = g_p0.toInt()
            DV.canvas.drawCircle(g_x0.toFloat(), g_y0.toFloat(), 0.5.toFloat(), DV.paint)
            return
        }
        if (gPIndex == 1) {
            g_x1 = x * scale + offsetX + 0.1f
            g_y1 = y * scale + offsetY
            g_p1 = Math.max(1f, penWidth.toFloat() * scale * force.toFloat() / 1023)
            width1 = g_p1.toInt()
            g_vx01 = g_x1 - g_x0
            g_vy01 = g_y1 - g_y0
            // instead of dividing tangent/norm by two, we multiply norm by 2
            g_norm = Math.sqrt((g_vx01 * g_vx01 + g_vy01 * g_vy01 + 0.0001f).toDouble()).toFloat() * 2f
            g_vx01 = g_vx01 / g_norm * g_p0
            g_vy01 = g_vy01 / g_norm * g_p0
            g_n_x0 = g_vy01
            g_n_y0 = -g_vx01
            return
        }
        if (gPIndex > 1 && gPIndex < 10000) {
            g_x3 = x * scale + offsetX + 0.1f
            g_y3 = y * scale + offsetY
            g_p3 = Math.max(1f, penWidth.toFloat() * scale * force.toFloat() / 1023)
            width1 = g_p3.toInt()
            g_x2 = (g_x1 + g_x3) / 2f
            g_y2 = (g_y1 + g_y3) / 2f
            g_p2 = (g_p1 + g_p3) / 2f
            g_vx21 = g_x1 - g_x2
            g_vy21 = g_y1 - g_y2
            g_norm = Math.sqrt((g_vx21 * g_vx21 + g_vy21 * g_vy21 + 0.0001f).toDouble()).toFloat() * 2f
            g_vx21 = g_vx21 / g_norm * g_p2
            g_vy21 = g_vy21 / g_norm * g_p2
            g_n_x2 = -g_vy21
            g_n_y2 = g_vx21
            mDrawPath.rewind()
            mDrawPath.moveTo(g_x0 + g_n_x0, g_y0 + g_n_y0)
            mDrawPath.cubicTo(g_x1 + g_n_x0, g_y1 + g_n_y0, g_x1 + g_n_x2, g_y1 + g_n_y2, g_x2 + g_n_x2, g_y2 + g_n_y2)
            mDrawPath.cubicTo(g_x2 + g_n_x2 - g_vx21, g_y2 + g_n_y2 - g_vy21, g_x2 - g_n_x2 - g_vx21, g_y2 - g_n_y2 - g_vy21, g_x2 - g_n_x2, g_y2 - g_n_y2)
            mDrawPath.cubicTo(g_x1 - g_n_x2, g_y1 - g_n_y2, g_x1 - g_n_x0, g_y1 - g_n_y0, g_x0 - g_n_x0, g_y0 - g_n_y0)
            mDrawPath.cubicTo(g_x0 - g_n_x0 - g_vx01, g_y0 - g_n_y0 - g_vy01, g_x0 + g_n_x0 - g_vx01, g_y0 + g_n_y0 - g_vy01, g_x0 + g_n_x0, g_y0 + g_n_y0)
            DV.canvas.drawPath(mDrawPath, DV.paint)
            g_x0 = g_x2
            g_y0 = g_y2
            g_p0 = g_p2
            g_x1 = g_x3
            g_y1 = g_y3
            g_p1 = g_p3
            g_vx01 = -g_vx21
            g_vy01 = -g_vy21
            g_n_x0 = g_n_x2
            g_n_y0 = g_n_y2
            return
        }
        if (gPIndex >= 10000) {//Last Point
            g_x2 = x * scale + offsetX + 0.1f
            g_y2 = y * scale + offsetY
            g_p2 = Math.max(1f, penWidth.toFloat() * scale * force.toFloat() / 1023)
            width1 = g_p2.toInt()
            g_vx21 = g_x1 - g_x2
            g_vy21 = g_y1 - g_y2
            g_norm = Math.sqrt((g_vx21 * g_vx21 + g_vy21 * g_vy21 + 0.0001f).toDouble()).toFloat() * 2f
            g_vx21 = g_vx21 / g_norm * g_p2
            g_vy21 = g_vy21 / g_norm * g_p2
            g_n_x2 = -g_vy21
            g_n_y2 = g_vx21

            mDrawPath.rewind()
            mDrawPath.moveTo(g_x0 + g_n_x0, g_y0 + g_n_y0)
            mDrawPath.cubicTo(g_x1 + g_n_x0, g_y1 + g_n_y0, g_x1 + g_n_x2, g_y1 + g_n_y2, g_x2 + g_n_x2, g_y2 + g_n_y2)
            mDrawPath.cubicTo(g_x2 + g_n_x2 - g_vx21, g_y2 + g_n_y2 - g_vy21, g_x2 - g_n_x2 - g_vx21, g_y2 - g_n_y2 - g_vy21, g_x2 - g_n_x2, g_y2 - g_n_y2)
            mDrawPath.cubicTo(g_x1 - g_n_x2, g_y1 - g_n_y2, g_x1 - g_n_x0, g_y1 - g_n_y0, g_x0 - g_n_x0, g_y0 - g_n_y0)
            mDrawPath.cubicTo(g_x0 - g_n_x0 - g_vx01, g_y0 - g_n_y0 - g_vy01, g_x0 + g_n_x0 - g_vx01, g_y0 + g_n_y0 - g_vy01, g_x0 + g_n_x0, g_y0 + g_n_y0)
            DV.canvas.drawPath(mDrawPath, DV.paint)
            return
        }
    }

    private fun drawSubFountainPen1(DV: DrawView, scale: Float, offsetX: Float,
                                    offsetY: Float, penWidth: Int, x: Float, y: Float, force: Int, ntype: Int, color: Int) {
        if (ntype == 0) {
            g_x0 = x
            g_y0 = y
            g_x1 = x
            g_y1 = y
        }
        g_x1 = x
        g_y1 = y
        Log.e(TAG, "111111111111")
        if (ntype == 2) {
            return
        }

        Log.e(TAG, "2222222222222" + g_x0 + g_y0 + g_x1 + g_y1)
        mDrawPath.rewind()

        DV.paint.setStrokeWidth(penWidth.toFloat())
        SetPenColor(color)
        //mDrawPath.moveTo( g_x0 + g_n_x0, g_y0 + g_n_y0 );
        DV.canvas.drawLine(g_x0, g_y0, g_x1, g_y1, DV.paint)

        g_x0 = g_x1
        g_y0 = g_y1
        return

    }


    // 生成文件夹
    fun makeRootDirectory(filePath: String) {
        var file: File? = null
        try {
            file = File(filePath)
            if (!file.exists()) {
                file.mkdir()
            }
        } catch (e: Exception) {
            Log.e("error:", e.toString() + "")
        }

    }

    fun DrawExistingStroke(PageID: Int) {
        Log.e(TAG, "======draw his==========")
        val keys = dot_number!!.keySet()
        for (key in keys) {
            Log.e(TAG, "=========pageID=======$PageID=====Key=====$key")
            if (key == PageID) {
                val dots = dot_number!!.get(key)
                for (dot in dots) {
                    Log.e(TAG, "=========pageID=======" + dot.pointX + "====" + dot.pointY + "===" + dot.ntype)
                    drawSubFountainPen1(bDrawl[0]!!, gScale, gOffsetX, gOffsetY, dot.penWidth,
                            dot.pointX, dot.pointY, dot.force, dot.ntype, dot.ncolor)
                }
            }
        }
        gPIndex = -1
    }

    fun drawInit() {
        count = 0
        bDrawl[0]!!.initDraw()
//        bDrawl[0]!!.setVcolor(Color.WHITE)
        bDrawl[0]!!.setVwidth(1)
        if (color == 0) {
            bDrawl[0]!!.paint.color = Color.BLACK;
        } else {
            bDrawl[0]!!.paint.color = Color.parseColor("#" + TypeUtils.toHex(color)
                    .toString().toUpperCase())
        }
        //20170430
        //bDrawl[0].paint.setColor( Color.WHITE );
        SetPenColor(gColor)
        bDrawl[0]!!.paint.strokeCap = Paint.Cap.ROUND
        bDrawl[0]!!.paint.style = Paint.Style.FILL
        bDrawl[0]!!.paint.isAntiAlias = true
        bDrawl[0]!!.invalidate()

        //20170519
        if (gbSetNormal == true) {
            val para: ViewGroup.LayoutParams
            para = gImageView.layoutParams

            para.width = (BG_WIDTH * gScale).toInt()
            para.height = (BG_HEIGHT * gScale).toInt()

            if (gbCover == false) {
                para.width = (BG_WIDTH1 * gScale).toInt()
                para.height = (BG_HEIGHT1 * gScale).toInt()
            }

            Log.e(TAG, "========BG_HEIGHT====$BG_WIDTH=====$BG_HEIGHT")
            gImageView.layoutParams = para
            //gLayout.setLayoutParams(para);
        }
    }

    private fun SetBackgroundImage(PageID: Int) {
        if (gbSetNormal == false) {
            val para: ViewGroup.LayoutParams
            para = gImageView.getLayoutParams()
            //Log.e(TAG,"SetBack ImageView width:" + para.width + ", height:" + para.height);
            para.width = BG_WIDTH
            para.height = BG_HEIGHT
            gImageView.setLayoutParams(para)
            //gLayout.setLayoutParams(para);
            //Log.e(TAG,"SetBack111 ImageView width:" + para.width + ", height:" + para.height);
            gbSetNormal = true

        }
        gbCover = true
        bDrawl[0]!!.canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
        //bDrawl[0].setLayerType(View.LAYER_TYPE_NONE, null);
        Log.e(TAG, "SetBackgroundImage----" + PageID)
        if (bIsA5size) {
            pageIdIndex = PageID
            saveDraw(filePath, PageID.toString(), BitMaps.captureView(gImageView))
            when (PageID) {
                0 -> {
                    if (bIsA5size) {
                        Log.e(TAG, "--------bIsA5size1----------" + bIsA5size)
                        gImageView.setImageResource(R.drawable.p0)
                    }
                    return
                }
                1 -> {
                    if (bIsA5size) {
                        Log.e(TAG, "--------bIsA5size1----------" + bIsA5size)
                        gImageView.setImageResource(R.drawable.p1)
                    }
                    return
                }
                2 -> {
                    val view = gImageView.background

                    gImageView.setImageResource(R.drawable.p2)
                    return
                }
                3 -> {
                    gImageView.setImageResource(R.drawable.p3)
                    return
                }
                4 -> {
                    gImageView.setImageResource(R.drawable.p4)
                    return
                }
                5 -> {
                    gImageView.setImageResource(R.drawable.p5)
                    return
                }
                6 -> {
                    gImageView.setImageResource(R.drawable.p6)
                    return
                }
                7 -> {
                    gImageView.setImageResource(R.drawable.p7)
                    return
                }
                8 -> {
                    gImageView.setImageResource(R.drawable.p8)
                    return
                }
                9 -> {
                    gImageView.setImageResource(R.drawable.p9)
                    return
                }
                10 -> {
                    gImageView.setImageResource(R.drawable.p10)
                    return
                }
                11 -> {
                    gImageView.setImageResource(R.drawable.p11)
                    return
                }
                12 -> {
                    gImageView.setImageResource(R.drawable.p12)
                    return
                }
                13 -> {
                    gImageView.setImageResource(R.drawable.p13)
                    return
                }
                14 -> {
                    gImageView.setImageResource(R.drawable.p14)
                    return
                }
                15 -> {
                    gImageView.setImageResource(R.drawable.p15)
                    return
                }
                16 -> {
                    gImageView.setImageResource(R.drawable.p16)
                    return
                }
                17 -> {
                    gImageView.setImageResource(R.drawable.p17)
                    return
                }
                18 -> {
                    gImageView.setImageResource(R.drawable.p18)
                    return
                }
                19 -> {
                    gImageView.setImageResource(R.drawable.p19)
                    return
                }
                20 -> {
                    gImageView.setImageResource(R.drawable.p20)
                    return
                }
                21 -> {
                    gImageView.setImageResource(R.drawable.p21)
                    return
                }
                22 -> {
                    gImageView.setImageResource(R.drawable.p22)
                    return
                }
                23 -> {
                    gImageView.setImageResource(R.drawable.p23)
                    return
                }
                24 -> {
                    gImageView.setImageResource(R.drawable.p24)
                    return
                }
                25 -> {
                    gImageView.setImageResource(R.drawable.p25)
                    return
                }
                26 -> {
                    gImageView.setImageResource(R.drawable.p26)
                    return
                }
                27 -> {
                    gImageView.setImageResource(R.drawable.p27)
                    return
                }
                28 -> {
                    gImageView.setImageResource(R.drawable.p28)
                    return
                }
                29 -> {
                    gImageView.setImageResource(R.drawable.p29)
                    return
                }
                30 -> {
                    gImageView.setImageResource(R.drawable.p30)
                    return
                }
                31 -> {
                    gImageView.setImageResource(R.drawable.p31)
                    return
                }
                32 -> {
                    gImageView.setImageResource(R.drawable.p32)
                    return
                }
                33 -> {
                    gImageView.setImageResource(R.drawable.p33)
                    return
                }
                34 -> {
                    gImageView.setImageResource(R.drawable.p34)
                    return
                }
                35 -> {
                    gImageView.setImageResource(R.drawable.p35)
                    return
                }
                36 -> {
                    gImageView.setImageResource(R.drawable.p36)
                    return
                }
                37 -> {
                    gImageView.setImageResource(R.drawable.p37)
                    return
                }
                38 -> {
                    gImageView.setImageResource(R.drawable.p38)
                    return
                }
                39 -> {
                    gImageView.setImageResource(R.drawable.p39)
                    return
                }
                40 -> {
                    gImageView.setImageResource(R.drawable.p40)
                    return
                }
                41 -> {
                    gImageView.setImageResource(R.drawable.p41)
                    return
                }
                42 -> {
                    gImageView.setImageResource(R.drawable.p42)
                    return
                }
                43 -> {
                    gImageView.setImageResource(R.drawable.p43)
                    return
                }
                44 -> {
                    gImageView.setImageResource(R.drawable.p44)
                    return
                }
                45 -> {
                    gImageView.setImageResource(R.drawable.p45)
                    return
                }
                46 -> {
                    gImageView.setImageResource(R.drawable.p46)
                    return
                }
                47 -> {
                    gImageView.setImageResource(R.drawable.p47)
                    return
                }
                48 -> {
                    gImageView.setImageResource(R.drawable.p48)
                    return
                }
                49 -> {
                    gImageView.setImageResource(R.drawable.p49)
                    return
                }
                50 -> {
                    gImageView.setImageResource(R.drawable.p50)
                    return
                }
                51 -> {
                    gImageView.setImageResource(R.drawable.p51)
                    return
                }
                52 -> {
                    gImageView.setImageResource(R.drawable.p52)
                    return
                }
                53 -> {
                    gImageView.setImageResource(R.drawable.p53)
                    return
                }
                54 -> {
                    gImageView.setImageResource(R.drawable.p54)
                    return
                }
                55 -> {
                    gImageView.setImageResource(R.drawable.p55)
                    return
                }
                56 -> {
                    gImageView.setImageResource(R.drawable.p56)
                    return
                }
                57 -> {
                    gImageView.setImageResource(R.drawable.p57)
                    return
                }
                58 -> {
                    gImageView.setImageResource(R.drawable.p58)
                    return
                }
                59 -> {
                    gImageView.setImageResource(R.drawable.p59)
                    return
                }
                60 -> {
                    gImageView.setImageResource(R.drawable.p60)
                    return
                }
                61 -> {
                    gImageView.setImageResource(R.drawable.p61)
                    return
                }
                62 -> {
                    gImageView.setImageResource(R.drawable.p62)
                    return
                }
                63 -> {
                    gImageView.setImageResource(R.drawable.p63)
                    return
                }
                64 -> {
                    gImageView.setImageResource(R.drawable.p64)
                    return
                }
                65 -> {
                    gImageView.setImageResource(R.drawable.p65)
                    return
                }
                66 -> {
                    gImageView.setImageResource(R.drawable.p66)
                    return
                }
                67 -> {
                    gImageView.setImageResource(R.drawable.p67)
                    return
                }
                68 -> {
                    gImageView.setImageResource(R.drawable.p68)
                    return
                }
                69 -> {
                    gImageView.setImageResource(R.drawable.p69)
                    return
                }
                70 -> {
                    gImageView.setImageResource(R.drawable.p70)
                    return
                }
                71 -> {
                    gImageView.setImageResource(R.drawable.p71)
                    return
                }
                72 -> {
                    gImageView.setImageResource(R.drawable.p72)
                    return
                }
                73 -> {
                    gImageView.setImageResource(R.drawable.p73)
                    return
                }
                74 -> {
                    gImageView.setImageResource(R.drawable.p74)
                    return
                }
                75 -> {
                    gImageView.setImageResource(R.drawable.p75)
                    return
                }
                76 -> {
                    gImageView.setImageResource(R.drawable.p76)
                    return
                }
                77 -> {
                    gImageView.setImageResource(R.drawable.p77)
                    return
                }
                78 -> {
                    gImageView.setImageResource(R.drawable.p78)
                    return
                }
                79 -> {
                    gImageView.setImageResource(R.drawable.p79)
                    return
                }
                80 -> {
                    gImageView.setImageResource(R.drawable.p80)
                    return
                }
                81 -> {
                    gImageView.setImageResource(R.drawable.p81)
                    return
                }
                82 -> {
                    gImageView.setImageResource(R.drawable.p82)
                    return
                }
                83 -> {
                    gImageView.setImageResource(R.drawable.p83)
                    return
                }
                84 -> {
                    gImageView.setImageResource(R.drawable.p84)
                    return
                }
                85 -> {
                    gImageView.setImageResource(R.drawable.p85)
                    return
                }
                86 -> {
                    gImageView.setImageResource(R.drawable.p86)
                    return
                }
                87 -> {
                    gImageView.setImageResource(R.drawable.p87)
                    return
                }
                88 -> {
                    gImageView.setImageResource(R.drawable.p88)
                    return
                }
                89 -> {
                    gImageView.setImageResource(R.drawable.p89)
                    return
                }
                90 -> {
                    gImageView.setImageResource(R.drawable.p90)
                    return
                }
                91 -> {
                    gImageView.setImageResource(R.drawable.p91)
                    return
                }
                92 -> {
                    gImageView.setImageResource(R.drawable.p92)
                    return
                }
                93 -> {
                    gImageView.setImageResource(R.drawable.p93)
                    return
                }
                94 -> {
                    gImageView.setImageResource(R.drawable.p94)
                    return
                }
                95 -> {
                    gImageView.setImageResource(R.drawable.p95)
                    return
                }
                else -> Log.e(TAG, "setImageResource error index = " + PageID)
            }
        }
    }

    internal var isConnected = false
    private var disConnectTime: Long = 0
    private var connectNum = 0

    private val mGattUpdateReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            isConnected = true
            if (BluetoothLEService.ACTION_GATT_CONNECTED.equals(action)) {
                bDrawl[0]!!.canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
//                updateConnectionState(R.string.connected)
                toast("连接成功")
//                invalidateOptionsMenu()
                //bleManager.ReqAdjustRTC();
                val format1 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                val str = format1.format(java.util.Date())

                try {
                    //String str = "2010-01-02 00:00:00";
                    val str1 = "2010-01-01 00:00:00"
                    val d1 = format1.parse(str)
                    val d2 = format1.parse(str1)

                    val diff = (d1.time - d2.time) / 1000
                    Log.e(TAG, "========rtc=======" + str + "----------" + d1.time + ", " + d2.time + ", " + diff)
                    //bleManager.ReqSetupPenRTCTime(diff);
                } catch (e: Exception) {
                }
            }
            if (BluetoothLEService.ACTION_GATT_DISCONNECTED.equals(action)) {
                if (connectNum > 0) {
                    connectNum--
                }
                // 记录断线时的时间戳
                val format1 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                val str = format1.format(java.util.Date())

                try {
                    val d1 = format1.parse(str)
                    disConnectTime = d1.time / 1000
                } catch (e: Exception) {
                }

                // 关闭ObjectOutputStream
                try {
                    oos!!.close()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                gbCover = false
                isConnected = false
                bDrawl[0]!!.canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
                dot_number!!.clear()
                toast("断开连接")
//                updateConnectionState(R.string.disconnected)
//                invalidateOptionsMenu()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        bDrawl[0]!!.DrawDestroy()
        c.unbindService(mServiceConnection)
        mService!!.stopSelf()
        mService = null

        stroke_c = null
        dot_number!!.clear()
        dot_number = null

    }

    private fun makeGattUpdateIntentFilter(): IntentFilter {
        val intentFilter = IntentFilter()
        intentFilter.addAction(BluetoothLEService.ACTION_GATT_CONNECTED)
        intentFilter.addAction(BluetoothLEService.ACTION_GATT_DISCONNECTED)
        intentFilter.addAction(BluetoothLEService.ACTION_GATT_SERVICES_DISCOVERED)
        intentFilter.addAction(BluetoothLEService.ACTION_DATA_AVAILABLE)
        intentFilter.addAction(BluetoothLEService.RECEVICE_DOT)
        return intentFilter
    }

    override fun onResume() {
        super.onResume()
        c.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter())
    }

    override fun onPause() {
        super.onPause()
        c.unregisterReceiver(mGattUpdateReceiver)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
        bitmap!!.recycle()
        bitmap = null

        bitmpResult!!.recycle()
        bitmpResult = null
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun messageEvent(event: ColorEvent) {
        color = event.color
        gColor = event.color
        SetPenColor(color)
    }

    private var colors = IntArray(4)

    fun SetPenColor(ColorIndex: Int) {
        colors = ColorUtils.changeArgb(ColorIndex)
        bDrawl[0]!!.paint.color = Color.rgb(colors[1], colors[2], colors[3])
    }
}